<template>
  <div class="home homeBottomo">
    <el-card class="card-container">
      <div class="container" :style="{ height: statusHeight }">
        <!-- 左边 -->
        <div class="card-left">
          <!-- 设备总数 -->
          <div class="left">
            <p class="yellow">{{ devicesStore.$state.deviceCount?.TotalCount ? devicesStore.$state.deviceCount?.TotalCount : 0 }}</p>
            <span>终端总数</span>
          </div>
          <!-- 运行数 -->
          <div class="margin-LR border">
            <p class="green">{{ devicesStore.$state.deviceCount?.WorkCount ? devicesStore.$state.deviceCount?.WorkCount : 0 }}</p>
            <span>运行数</span>
          </div>
          <!-- 故障数 -->
          <div class="margin-LR">
            <p class="red">{{ devicesStore.$state.deviceCount?.FaultCount ? devicesStore.$state.deviceCount?.FaultCount : 0 }}</p>
            <span>故障数</span>
          </div>
          <!-- 待机数 -->
          <div class="margin-LR border">
            <p class="gray">{{ devicesStore.$state.deviceCount?.StandbyCount ? devicesStore.$state.deviceCount?.StandbyCount : 0 }}</p>
            <span>待机数</span>
          </div>
          <!-- 离线数 -->
          <div class="margin-LR">
            <p class="gray">{{ devicesStore.$state.deviceCount?.OfflineCount ? devicesStore.$state.deviceCount?.OfflineCount : 0 }}</p>
            <span>离线数</span>
          </div>
        </div>
        <!--  右边 -->
        <div class="card-right">
          <!-- 3   4图标 -->
          <!-- <div class="mode-change" v-if="switchMode">
            <div v-for="mode in modes" :key="mode.num">
              <img :src="mode.icon" :alt="mode.alt" @click="changemode(mode.num)" v-show="mode.showValue" />
            </div>
          </div> -->
          <!-- 按钮 -->
          <div class="btn" @click="handlerSwitch">
            <img v-show="switchMode" src="./img/icon-switch-control.svg" alt="" />
            <p v-show="switchMode">控制模式</p>
            <img v-show="!switchMode" src="./img/icon-switch-monitor.svg" alt="" />
            <p v-show="!switchMode">监控模式</p>
          </div>
        </div>
      </div>
    </el-card>
    <div v-if="!showThreeAndFour && switchMode" class="showfour">
      <el-row :gutter="24">
        <el-col :span="conFour" v-for="device in devices" :key="device.DeviceId">
          <FourControlmode class="ShowfourItem" v-show="devices.length" :device="device" :devicecardWebscoket="devicecardWebscoket" :alarmcardWebscoket="alarmcardWebscoket">
          </FourControlmode>
        </el-col>
        <ControlModeEmpty v-show="!devices.length"></ControlModeEmpty>
      </el-row>
    </div>
    <!-- 控制模式 -->
    <div v-if="showThreeAndFour && switchMode" class="showthree">
      <el-row :gutter="24">
        <el-col :span="conThree" v-for="device in devices" :key="device.DeviceId">
          <ControlMode class="ShowthreeItem" v-show="devices.length" :device="device" :devicecardWebscoket="devicecardWebscoket" :alarmcardWebscoket="alarmcardWebscoket">
          </ControlMode>
        </el-col>
      </el-row>
      <ControlModeEmpty v-show="!devices.length"></ControlModeEmpty>
    </div>

    <!-- <div:class="{ 'control': isflex, 'control-start': !isflex }"> -->

    <!-- <ControlModeEmpty v-show="devices.length<1"></ControlModeEmpty> -->
    <!-- 监控模式 -->
    <div class="monitor" v-show="!switchMode">
      <MonitorMode :devicecardWebscoket="devicecardWebscoket"></MonitorMode>
    </div>
  </div>
</template>
<script lang="ts" setup>
// 引入组件
import MonitorMode from "@/views/MonitorMode/monitormode.vue";
import ControlMode from "@/views/ControlMode/controlmode.vue";
import FourControlmode from "@/views/FourAndControMode/FourAndcontromode.vue"
import ControlModeEmpty from "@/views/ControlModeEmpty/controlmodeempty.vue";
import Head from "@/components/Head/head.vue";

import iconThree from "@/views/Home/img/icon-Three.svg"
import iconFour from "@/views/Home/img/icon-Four.svg"
// 引入vue中的
import { computed, onMounted, ref, onBeforeUnmount, onUnmounted, watch, reactive, watchEffect } from "vue";
//用户登录相关的小仓库
import { useDevicesStore } from "@/stores/devices";
import { useUserInfoStore } from "@/stores/userInfo";
import { useRouter } from "vue-router";
// serverConfig.json是一个JSON格式的配置文件，用于存储服务器的配置信息
import serverConfig from "../../../serverConfig.json";
// 定义基础路径
const baseURL = `http://${serverConfig.server.ip}`;
const { currentRoute } = useRouter();
// 导入SignalR
import * as signalR from "@microsoft/signalr";

// 浏览器的宽高
const windowWidth = ref(0)
const windowHeight = ref(0)
const isflex = ref(false)
// 3*3的时候根据浏览器宽度展示几列
const conThree = ref(8);
const conFour = ref(6);
// 状态栏在3*3和4*4的高度变化
const statusHeight = ref<any>('92px')
const ThreeImg = iconThree
const FourImg = iconFour
const showThreeAndFour = ref(true)
// 获取设备小仓库
const devicesStore = useDevicesStore();
const userInfoStore = useUserInfoStore();
// 定义3*3模式与4*4模式的切换
const ThreeAndFourMode = ref(true);
// 定义监控模式与控制模式的切换
const switchMode = ref(true);
// 定义websocket返回来的数据
// const empty = ref(true);
// 定义监控卡片信息的变量
const devicecardWebscoket = ref<any>([]);
// 定义监控告警信息的变量
const alarmcardWebscoket = ref<any>([]);
// 定义基本服务信息的变量
const basicservicesWebscoket = ref<any>([]);
// 定义SignalR服务器地址
// 连接设备监控卡片信息
const connection = new signalR.HubConnectionBuilder()
  .withUrl(`${baseURL}:10751/terminalcard`, {
    skipNegotiation: true,
    transport: signalR.HttpTransportType.WebSockets,
  }) // 替换为实际的SignalR服务器地址
  .withAutomaticReconnect()
  .configureLogging(signalR.LogLevel.Information) // 使用signalr-protocol-msgpack
  .build();
// 连接设备监控告警信息
const connection1 = new signalR.HubConnectionBuilder()
  .withUrl(`${baseURL}:10751/alarm`, {
    skipNegotiation: true,
    transport: signalR.HttpTransportType.WebSockets,
  }) // 替换为实际的SignalR服务器地址
  .withAutomaticReconnect()
  .configureLogging(signalR.LogLevel.Information) // 使用signalr-protocol-msgpack
  .build();

const connectWebSockets = () => {
  // 连接设备监控卡片信息
  connection.on("TerminalCardReceived", (message) => {
    // console.log("🚀 ~ file: home.vue:131 ~ connection.on ~ message:", message)
    // if (!message.WorkStatus || !message.StatisticResults || !message.Hardware) return
    // setTimeout(() => {
    // 查找数组中是否存在相同的 id 和 num
    const existingItem = devicecardWebscoket.value.find((item: any) => item.TerminalIdentity == message.TerminalIdentity && item.StatisticResults?.TotalCount == message.StatisticResults?.TotalCount && item.WorkStatus?.WorkStatus == message.WorkStatus?.WorkStatus);

    if (!existingItem) {
      // 查找数组中是否存在相同的 id
      const existingIndex = devicecardWebscoket.value.findIndex((item: any) => item.TerminalIdentity == message.TerminalIdentity);
      if (existingIndex !== -1) {
        // 如果存在相同的 id，但 num 不同，则进行替换
        devicecardWebscoket.value.splice(existingIndex, 1, message);
      } else {
        // 如果 id 和 num 都不同，则进行追加
        devicecardWebscoket.value.push(message);
      }

      const prioritizeRed = (devicecardWebscoket: any) => {
        devicecardWebscoket.sort((a: any, b: any) => {
          if (a.WorkStatus.WorkStatus == 'Work' && b.WorkStatus.WorkStatus != 'Work') {
            return -1; // a排在前面
          } else if (a.WorkStatus.WorkStatus != 'Work' && b.WorkStatus.WorkStatus == 'Work') {
            return 1;  // b排在前面
          } else if (a.WorkStatus.WorkStatus == 'Standby' && b.WorkStatus.WorkStatus != 'Standby') {
            return -1; // a排在前面
          } else if (a.WorkStatus.WorkStatus != 'Standby' && b.WorkStatus.WorkStatus == 'Standby') {
            return 1;  // b排在前面
          } else {
            return 0;  // 相对顺序不变
          }
        });
        return devicecardWebscoket;
      }

    }
    // }, 1000)

  });
  // 连接设备监控告警信息
  connection1.on("AlarmReceived", (message) => {
    const existingItem = alarmcardWebscoket.value.find((item: any) => item.TerminalIdentity === message.TerminalIdentity && item.AlarmTime === message.AlarmTime);
    if (!existingItem) {
      // 查找数组中是否存在相同的 id
      const existingIndex = alarmcardWebscoket.value.findIndex((item: any) => item.TerminalIdentity === message.TerminalIdentity);
      if (existingIndex !== -1) {
        // 如果存在相同的 id，但 num 不同，则进行替换
        alarmcardWebscoket.value.splice(existingIndex, 1, message);
      } else {
        // 如果 id 和 num 都不同，则进行追加
        alarmcardWebscoket.value.push(message);
      }
    }
  });

  // 开始连接
  // 连接设备监控卡片信息
  connection.start().then(() => { console.log("设备监控卡片信息SignalR连接已建立"); }).catch((error) => { console.error("设备监控卡片信息SignalR连接错误:", error); });
  // 连接设备监控告警信息
  connection1.start().then(() => { console.log("设备监控告警信息SignalR连接已建立"); }).catch((error) => { console.error("设备监控告警信息SignalR连接错误:", error); });

}
const connectWebSockets1 = () => {
  // 关闭连接
  // 连接设备监控卡片信息
  connection.stop().then(() => { console.log("设备监控卡片信息SignalR已关闭"); })
  connection1.stop().then(() => { console.log("设备监控卡片信息SignalR已关闭"); })
  clearInterval(timerId);
}
const modes = ref([
  { icon: ThreeImg, alt: '3×3', num: 3, showValue: true },
  { icon: FourImg, alt: '4×4', num: 4, showValue: false }
])

const changemode = (num: any) => {
  modes.value.map((item: any) => {
    item.showValue = !item.showValue
  })
  if (num == 3) {
    showThreeAndFour.value = false
    statusHeight.value = '84px'
  } else {
    showThreeAndFour.value = true
    statusHeight.value = '92px'
  }

}

// 获取所有设备信息的功能函数
const getDevices = async () => {
  // 请求获取所有设备信息
  await devicesStore.Alldevice();
  // empty.value = false;
};

// 获取终端信息计数器的功能函数
const getCount = async () => {
  // 请求获取所有设备信息
  await devicesStore.count();
  // empty.value = false;
};

// 获取所有用户信息
const getUsers = async () => {

  await userInfoStore.usersinfo();
};
// 从仓库中拿数据
const devices: any = ref(computed(() => devicesStore.$state.devices));

// 控制模式与监控模式的切换的点击事件
const handlerSwitch = () => {
  switchMode.value = !switchMode.value;
}
const timerId = setInterval(() => {
  getCount()
}, 3000)

const getWindowSize = () => {
  isflex.value = window.innerWidth >= 1870;
}
// const getWindowSize = () => {
//   windowWidth.value = window.innerWidth;
//   windowHeight.value = window.innerHeight;
// }
// 页面挂在发请求
onMounted(async () => {
  const handleResize = () => {
    if ((window.innerWidth < 1600 || window.innerWidth == 1600) && (window.innerWidth > 1400 || window.innerWidth == 1400)) {
      conThree.value = 12;
      conFour.value = 8
    } else if (window.innerWidth < 1400 && window.innerWidth > 1075) {
      conFour.value = 12
    }
    else if (window.innerWidth < 1075) {
      conThree.value = 12;
    } else {
      conThree.value = 8;
      conFour.value = 6
    }
  };

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize);
  getWindowSize()
  await getUsers()
  window.addEventListener('resize', getWindowSize);
  await getCount()
  // 在组件加载时建立WebSocket连接
  connectWebSockets()
  // 获取所有设备的信息
  await getDevices();
  getUsers()
});

onBeforeUnmount(() => {
  connectWebSockets1()
  window.removeEventListener('resize', getWindowSize);
})

watchEffect(() => {
  const handleResize = () => {
    if ((window.innerWidth < 1600 && window.innerWidth > 1075) || window.innerWidth == 1600) {
      conThree.value = 12;
    } else if (window.innerWidth < 1075 && window.innerWidth > 502) {
      conThree.value = 24;
    } else {
      conThree.value = 8;
    }
  };

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize);

  // 在组件卸载时移除事件监听
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
  });
});
</script>

<style scoped lang="less">
@import url(//at.alicdn.com/t/c/font_3891677_7o5y8y34wsb.css);
@media screen and (min-width: 1921px) {

  .ShowthreeItem {
    margin-bottom: 10px;
  }
}
@media screen and (max-width: 1920px) {
  .control:after {
    content: "";
    display: block;
    width: 595px;
  }

  .ShowthreeItem {
    margin-bottom: 0px;
  }
}

@media screen and (max-width: 1600px) {
  .ShowthreeItem {
    overflow: wrap;
    min-width: 491px;
    min-height: 240px;
    margin-bottom: 0px;
  }
}

@media screen and (max-width: 1076px) {
  .ShowthreeItem {
    overflow: wrap;
    min-width: 502px;
    flex-wrap: wrap;
    min-height: 240px;
    margin-bottom: 0px;
  }
}

@media screen and (max-height: 1440px) {
  .homeBottomo {
    height: 86%;
  }

  .controlBottom {
    height: 87%;
  }
}

@media screen and (max-height: 1080px) {
  .homeBottomo {
    height: 80%;
  }  

  .controlBottom {
    height: 85%;
  }
}

:deep(.el-card__body) {
  padding: 0;
}

.home {
  width: 100%;
  padding: 0 40px;
  font-size: 30px;

  /*卡片一*/
  .card-container {
    margin: 24px 0px 0px 0px;
    padding: 0 40px;
    border-radius: 4px;
    box-shadow: 0px 3px 6px 0px rgba(58, 58, 58, 0.05);

    .container {
      background: white;
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 92px;


      /*左边*/
      .card-left {
        display: flex;

        .margin-LR {
          display: flex;
          flex-direction: column;
          align-items: center;
          width: 128px;
        }

        p {
          font-family: "DINCond-Medium";
          font-style: normal;
          font-weight: 500;
          font-size: 28px;
          line-height: 28px;
        }

        span {
          font-style: normal;
          font-weight: 400;
          font-size: 14px;
          line-height: 22px;
          color: #595959;
        }

        .yellow {
          color: #f2994a;
        }

        .green {
          color: #1aa367;
        }

        .red {
          color: #eb5757;
        }

        .gray {
          color: #8c8c8c;
        }

        .border {
          border-left: 1px solid rgba(0, 0, 0, 0.06);
          border-right: 1px solid rgba(0, 0, 0, 0.06);
        }

        .left {
          display: flex;
          flex-direction: column;
          width: 128px;
        }
      }

      /*右边*/
      .card-right {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .mode-change {
          cursor: pointer;
        }

        /*模式按钮*/
        .btn {
          box-sizing: border-box;
          display: flex;
          justify-content: center;
          align-items: center;
          gap: 8px;
          width: 140px;
          height: 40px;
          background: #f2994a;
          border: 1px solid #fc9030;
          box-shadow: 0px 0px 8px rgba(242, 153, 74, 0.05),
            0px 8px 16px rgba(242, 153, 74, 0.25);
          border-radius: 8px;
          margin-left: 40px;
          cursor: pointer;

          p {
            font-family: "Source Han Sans CN";
            font-style: normal;
            font-weight: 500;
            font-size: 14px;
            line-height: 20px;
            color: #ffffff;
          }
        }
      }
    }
  }

  /*----------------4*4---------------------*/

  .showfour {
    width: 100%;
    overflow: hidden;
    height: 100%;
    overflow-y: auto;
    margin-top: 16px;

    .ShowfourItem {
      height: 17vh;
      min-height: 168px;
      max-height: 243px;
      margin-bottom: 16px;
      min-width: 442px;
    }

    &::-webkit-scrollbar-track-piece {
      background: #d3dce6;
    }

    &::-webkit-scrollbar {
      width: 0px;
    }

    &::-webkit-scrollbar-thumb {
      background: #99a9bf;
      border-radius: 20px;
    }
  }

  /*----------------4*4---------------------*/

  /*----------------3*3---------------------*/

  .showthree {
    width: 100%;
    overflow: hidden;
    height: 100%;
    overflow-y: auto;
    margin-top: 16px;

   
   /* .ShowthreeItem {
      height: 24vh;
      min-height: 240px;
      margin-bottom: 10px;
      max-height: 341px;
    }
*/
    &::-webkit-scrollbar-track-piece {
      background: #d3dce6;
    }

    &::-webkit-scrollbar {
      width: 0px;
    }

    &::-webkit-scrollbar-thumb {
      background: #99a9bf;
      border-radius: 20px;
    }
  }

  /*----------------3*3--------------------*/



  .control {
    overflow: scroll;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    margin: 24px 0px 0px 0px;
    height: 100%;


    &::-webkit-scrollbar-track-piece {
      background: #d3dce6;
    }

    &::-webkit-scrollbar {
      width: 0px;
    }

    &::-webkit-scrollbar-thumb {
      background: #99a9bf;
      border-radius: 20px;
    }
  }

  .control-start {
    overflow: scroll;
    display: flex;
    justify-content: start;
    flex-wrap: wrap;
    margin-right: 20px;
    height: 100%;


    &::-webkit-scrollbar-track-piece {
      background: #d3dce6;
    }

    &::-webkit-scrollbar {
      width: 0px;
    }

    &::-webkit-scrollbar-thumb {
      background: #99a9bf;
      border-radius: 20px;
    }

    .marginRight {
      margin-right: 24px;
    }
  }

  .monitor {}
}
</style>
